import co.paralleluniverse.fibers.Fiber;
import co.paralleluniverse.fibers.SuspendExecution;
import co.paralleluniverse.strands.channels.Channel;
import co.paralleluniverse.strands.channels.Channels;
import org.apache.commons.codec.binary.Hex;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ExecutionException;

public class Example {

    private static void printer(Channel<Integer> in) throws SuspendExecution, InterruptedException {
        Integer v;
        while ((v = in.receive()) != null) {
            System.out.println(v);
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException, SuspendExecution {
        //定义两个Channel
        Channel<Integer> naturals = Channels.newChannel(-1);
        Channel<Integer> squares = Channels.newChannel(-1);

        //运行两个Fiber实现.
        new Fiber(() -> {
            for (int i = 0; i < 10; i++)
                naturals.send(i);
            naturals.close();
        }).start();

        new Fiber(() -> {
            Integer v;
            while ((v = naturals.receive()) != null)
                squares.send(v * v);
            squares.close();
        }).start();

        printer(squares);
    }

    public void test() {
        Map<String, String> map = new TreeMap<>();
        map.put("mobile", "123456");
        map.put("pwd", "123");
        String secretKey = "应用key";
        StringBuffer str = new StringBuffer();
        map.forEach((key, value) -> str.append(key).append("=").append(value).append("&"));
        str.append("secret_key=").append(secretKey);
        String result = String2SHA256(str.toString());
    }

    private String String2SHA256(String str) {
        String encodeStr = "";
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            byte[] hash = messageDigest.digest(str.getBytes(StandardCharsets.UTF_8));
            encodeStr = Hex.encodeHexString(hash);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return encodeStr;
    }
}